package com.design.android.personnel.ui.other;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import com.design.android.personnel.AppContext;
import com.design.android.personnel.R;
import com.design.android.personnel.ui.EditPersonalActivity;
import com.design.android.personnel.ui.LoginActivity;

public class OtherFragment extends Fragment {

    private OtherViewModel notificationsViewModel;

    private Button logoutButton;
    private Button editPersonalButton;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
            ViewGroup container, Bundle savedInstanceState) {
        notificationsViewModel =
                ViewModelProviders.of(this).get(OtherViewModel.class);
        View root = inflater.inflate(R.layout.fragment_other, container, false);

        logoutButton = root.findViewById(R.id.logout);
        editPersonalButton = root.findViewById(R.id.edit_personal);

        logoutButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showNormalDialog();
            }
        });

        editPersonalButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), EditPersonalActivity.class);
                startActivity(intent);
            }
        });


        return root;
    }

    private void showNormalDialog() {
        final AlertDialog.Builder normalDialog = new AlertDialog.Builder(getContext());
        // 设置对话框标题
        normalDialog.setTitle("是否确认退出？");
        // 设置对话框消息提示
        normalDialog.setMessage("退出将清楚登录缓存，请确认已牢记密码。");
        normalDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                AppContext.setLoggedInUser(null);
                redirect2Login();
            }
        });
        normalDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 关闭对话框
                dialog.cancel();
            }
        });
        // 显示
        normalDialog.show();
    }

    private void redirect2Login() {
        Intent intent = new Intent(getContext(), LoginActivity.class);
        startActivity(intent);
        getActivity().finish();
    }
}
